﻿using P2PWeb.Common;
using P2PWeb.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.Entity;
using System.Data.Objects.DataClasses;

namespace P2PWeb.Controllers
{
    public class LendInfo
    {
        public Campaign Campaign { get; set; }

        [DisplayName("金额")]
        [Required(ErrorMessage = "请输入出借金额")]
        [RegularExpression("^[0-9]*$", ErrorMessage = "出借金额必须为数字")]
        [MoneyRange]
        public decimal PutMoney { get; set; }


    }

    public class LendController : BaseController
    {
        private bool CheckCampaign(Campaign campaign, out ContentResult result)
        {
            result = null;
            string script = "<script>alert('{0}');window.location='{1}';</script>";
            Uri urlReferrer = Request.UrlReferrer;
            if (urlReferrer == null)
            {
                urlReferrer = new Uri("/", UriKind.RelativeOrAbsolute);
            }
            if (campaign == null)
            {
                result = new ContentResult()
                {

                    Content = string.Format(script,
                        "找不到相应订单", urlReferrer.ToString())
                };
                return false;
            }
            if (campaign.IsDel)
            {
                result = new ContentResult()
                {
                    Content = string.Format(script,
                        "找不到相应订单", urlReferrer.ToString())
                };
                return false;
            }
            if ((CampaignState)campaign.Status != CampaignState.Financing)
            {
                result = new ContentResult()
                {
                    Content = string.Format(script,
                        "此订单的状态为:" + ((CampaignState)campaign.Status).GetDisplayName() + ",因此无法投标", urlReferrer.ToString())
                };
                return false;
            }
            if (campaign.AccountID == CurrentUserInfo.ID)
            {
                result = new ContentResult()
                {
                    Content = string.Format(script,
                        "无法出借给自己", urlReferrer.ToString())
                };
                return false;
            }
            if (CurrentUserInfo.Money <= 0)
            {
                result = new ContentResult()
                {
                    Content = string.Format(script,
                        "您当前余额不足,请去充值.", "/")
                };
                return false;
            }
            return true;
        }

        public ActionResult Lending(OrderDetail detail)
        {
            using (var context = new Repository<P2PModelContainer>())
            {
                var campaign = context.GetEntityByID<Campaign>(detail.Id, new List<string>() { "Account.AccountInfo" });
                var account = campaign.Account;
                var accountInfo = campaign.Account.AccountInfo;
                ContentResult result = null;
                if (!CheckCampaign(campaign, out result))
                {
                    return result;
                }

                if (ModelState.IsValid)
                {
                    var paidAmount = detail.LendMoney;
                    if (paidAmount + campaign.RealAmount > campaign.Amount)
                    {
                        paidAmount = campaign.Amount - campaign.RealAmount;

                    }
                    Account curAccount = context.GetEntityByID<Account>(CurrentUserInfo.ID);
                    curAccount.Money -= paidAmount.Value;
                    campaign.RealAmount += (int)paidAmount.Value;
                    if (campaign.RealAmount == campaign.Amount)
                    {
                        campaign.Status = (int)CampaignState.Finish;
                    }
                    Flight flight = new Flight();
                    flight.CampaignID = campaign.ID;
                    flight.Amount = (int)paidAmount.Value;
                    flight.AccountID = curAccount.ID;
                    flight.CreationTime = DateTime.Now;
                    flight.UpdateTime = DateTime.Now;
                    context.Add(flight);
                    context.Update(campaign);
                    context.Update(curAccount);
                    return RedirectToAction("Index", "MyLends");
                }
                return View("LendrsDetail", detail);
            }
        }
    }
}
